package com.lw.lost.fragments

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.lw.lost.adapters.UserAdapter
import com.lw.lost.databinding.FragmentFriendsBinding
import com.lw.lost.db.DBlost
import com.lw.lost.models.User
import com.lw.lost.utils.PreferenceUtils
import com.lw.lost.activity.FriendRequestActivity

class FriendsFragment : Fragment() {

    private var _binding: FragmentFriendsBinding? = null
    private val binding get() = _binding!!
    private lateinit var db: DBlost
    private lateinit var userAdapter: UserAdapter

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentFriendsBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        db = DBlost(requireContext())
        
        setupRecyclerView()
        loadFriends()
    }

    private fun setupRecyclerView() {
        userAdapter = UserAdapter()
        binding.recyclerView.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = userAdapter
        }

        // 设置下拉刷新
        binding.swipeRefresh.setOnRefreshListener {
            loadFriends()
        }
    }

    private fun loadFriends() {
        val currentUserId = PreferenceUtils.getUserId(requireContext())
        val cursor = db.userDao.getFriends(currentUserId)
        val friends = mutableListOf<User>()
        
        cursor.use {
            while (it.moveToNext()) {
                val userId = it.getLong(it.getColumnIndexOrThrow("userId"))
                // 获取与该好友的未读消息数
                val unreadCount = db.messageDao.getUnreadCountFromSender(currentUserId, userId)
                
                friends.add(
                    User(
                        userId = userId,
                        username = it.getString(it.getColumnIndexOrThrow("username")),
                        name = it.getString(it.getColumnIndexOrThrow("name")),
                        phone = it.getString(it.getColumnIndexOrThrow("phone")),
                        status = it.getInt(it.getColumnIndexOrThrow("status")),
                        gender = it.getInt(it.getColumnIndexOrThrow("gender")),
                        age = it.getInt(it.getColumnIndexOrThrow("age")),
                        avatar = it.getString(it.getColumnIndexOrThrow("avatar")),
                        unreadCount = unreadCount // 添加未读消息数
                    )
                )
            }
        }
        
        userAdapter.submitList(friends)
        binding.tvFriendCount.text = "好友数量：${friends.size}"
        binding.emptyView.visibility = if (friends.isEmpty()) View.VISIBLE else View.GONE
    }

    private fun checkFriendRequests() {
        val cursor = db.friendRequestDao.getRequestsByReceiverId(PreferenceUtils.getUserId(requireContext()))
        cursor.use { cursor ->
            if (cursor.count > 0) {
                binding.tvRequestCount.visibility = View.VISIBLE
                binding.tvRequestCount.text = "您有 ${cursor.count} 条好友请求待处理"
                binding.tvRequestCount.setOnClickListener {
                    startActivity(Intent(requireContext(), FriendRequestActivity::class.java))
                }
            } else {
                binding.tvRequestCount.visibility = View.GONE
            }
        }
    }

    override fun onResume() {
        super.onResume()
        checkFriendRequests()
        loadFriends()
        binding.swipeRefresh.isRefreshing = false
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
} 